package com.ruike.alisurface.base;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MqttMessageUtils;
import com.ruike.alisurface.R;
import com.ruike.alisurface.broadcastReceiver.NetWorkBroadcastReceiver;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.ui.Login_Aty;
import com.ruike.alisurface.ui.ShopMain_Aty;
import com.ruike.alisurface.ui.SystemStart_Aty;
import com.ruike.alisurface.ui.adv.Adv_Aty;
import com.ruike.alisurface.ui.settings.BindMachine_Aty;
import com.ruike.alisurface.ui.settings.NetWork_Aty;
import com.ruike.alisurface.ui.settings.Settings_Aty;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.QrcodeUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_frame.base.BaseActivity;
import com.voodoo.lib_frame.manager.ActivityManager;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_mqtt.MqttOperation;
import com.voodoo.lib_utils.CountDownTimer;
import com.voodoo.lib_utils.DeviceUtils;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.SharedUtils;
import com.voodoo.lib_utils.imageLoader.GlideImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;

/**
 * Author：voodoo
 * CreateTime：2021/06/07 007 下午 12:34
 * Description：在BaseActivity的基础上抽取的项目中的BaseAty
 */
public abstract class BaseAty extends BaseActivity implements NetWorkBroadcastReceiver.OnNetworkChangeListener {

    CountDownTimer pageCountDownTimer;
    NetWorkBroadcastReceiver netWorkBroadcastReceiver;

    TextView connectTypeTv; // 连接类型 4G/WIFI
    ImageView signalLevelImgv; // 信号等级
    TextView signalLevelTv; // 信号强弱等级展示
    TextView titlePhone;

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
//            L.i("注册EventBus", this.getComponentName());
            EventBus.getDefault().register(this);
        }

        MqttOperation.getInstance().setMqttTopicMessageListener(MqttMessageUtils.getInstance());


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            L.i(getClass().getSimpleName() + " 注册广播监听");
            if (netWorkBroadcastReceiver == null) {
                netWorkBroadcastReceiver = new NetWorkBroadcastReceiver();
                netWorkBroadcastReceiver.setOnNetworkChangeListener(this);
            }
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            registerReceiver(netWorkBroadcastReceiver, intentFilter);
        } else {
            L.i(getClass().getSimpleName() + " 解注册");
            unregisterReceiver(netWorkBroadcastReceiver);
        }
    }


    // 当一个Message Event提交的时候这个方法会被调用
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusResult(MsgEventBus event) {
        L.i("onMessageEvent： ", event.toString());
        if (SERVICE_TEL.equals(event.getType())) {
            String phone = new StringBuilder().append("机主电话").append("\n")
                    .append(SharedUtils.getInstance().getString(SERVICE_TEL, getString(R.string.noPhoneStr))).toString();
            titlePhone.setText(phone);
        }
    }


    /**
     * 初始化标题栏
     *
     * @param isQrcodeCanClick 右侧二维码是否可点击
     */
    protected void initTitleBar(boolean isQrcodeCanClick) {
        TextView text1valueTv = findViewById(R.id.title_version); // 版本号展示
        text1valueTv.setText(new StringBuffer().append("v").append(BuildConfig.VERSION_NAME));
        connectTypeTv = findViewById(R.id.titleBar_connectType_tv); // 连接类型 4G/WIFI
        signalLevelImgv = findViewById(R.id.titleBar_signalLevel_imgv); // 信号等级
        signalLevelTv = findViewById(R.id.titleBar_signalLevel_tv); // 信号强弱等级展示

        titlePhone = findViewById(R.id.title_phone_info); // 版本号展示
        titlePhone.setText(String.format("机主电话\n%s", SharedUtils.getInstance().getString(SERVICE_TEL, getString(R.string.noPhoneStr))));

        ImageView snQrCodeImgv = findViewById(R.id.title_qrcdoe); // SN二维码展示
        setDataSNcode(snQrCodeImgv);
        ImageView title_icon = findViewById(R.id.title_icon);
        String logo_img = SharedUtils.getInstance().getString(ShareKey.LOGOIMG,null);
        if (!TextUtils.isEmpty(logo_img)) {
            String Name = logo_img.substring(logo_img.lastIndexOf("/")).substring(1);
            File logoFile = new File(Constant.FilePath.ICON_PATH + Name);
            if (logoFile.exists()) {
                GlideImageLoader.getInstance().loadImage(this, logoFile.getAbsolutePath(), title_icon);
            }
        }
        if (isQrcodeCanClick) {
            snQrCodeImgv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    continuousClick();
                }
            });
        }
    }

    // ========================================================================== 界面倒计时和界面跳转

    /**
     * 开始界面的倒计时
     *
     * @param time         倒计时时长
     * @param showTv       展示的TextView
     * @param jumpActivity 倒计时结束后跳转的界面
     */
    protected void startCountdownTimer(int time, TextView showTv, Class jumpActivity) {
        if (time <= 0) {
            L.i("开始倒计时，直接跳转界面");
            startIntent(jumpActivity);
            return;
        }
        boolean isHaveTextView = showTv != null;
        cancelCountdownTimer();
        pageCountDownTimer = new CountDownTimer(time * 1_000, 1_000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int timeLeft = (int) (millisUntilFinished / 1000);
                L.d(String.format("剩余倒计时时长：%s", timeLeft));
                if (isHaveTextView) {
                    showTv.setText(String.valueOf(timeLeft) + " s");
                }
            }

            @Override
            public void onFinish() {
                startIntent(jumpActivity);
            }
        }.start();
    }

    /**
     * 跳转到指定的Activity，如果为空则跳转到主界面
     *
     * @param jumpActivity 目标界面
     */
    private void startIntent(Class jumpActivity) {

        String baseUserid = SharedUtils.getInstance().getString(BASEUSERID, "RK_test");
        if (baseUserid.equals("RK_test")) {
            startActivity(new Intent(this, BindMachine_Aty.class));
            finish();
            return;
        }

        boolean isWork = SharedUtils.getInstance().getBoolean(ShareKey.IS_NETWORK_STATUS, false);
        if (isWork) {
            startActivity(new Intent(this, NetWork_Aty.class));
            finish();
            return;
        }
        if (jumpActivity != null) {
            startActivity(new Intent(this, jumpActivity));
        } else {
            // 判断有没有广告，有则跳转到广告界面，没有则跳回主界面
            if (Constant.AdvType.NONE == SharedUtils.getInstance().getInt(Constant.AdvType.ADV_TYPE_KEY)) {
                L.i("无广告，跳转到商品详情界面");
                startActivity(new Intent(this, ShopMain_Aty.class));
            } else {
                L.i("有广告，跳转到广告界面");
                startActivity(new Intent(this, Adv_Aty.class));
            }
        }
        finish();
    }

    /**
     * 取消倒计时
     */
    protected void cancelCountdownTimer() {
        if (pageCountDownTimer != null) {
            pageCountDownTimer.cancel();
            pageCountDownTimer = null;
            L.i("取消倒计时");

        }
    }

    // ========================================================================== 界面倒计时和界面跳转

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 2000;// 规定有效时间
    long[] mHits = new long[COUNTS];

    /**
     * 多次连续点击
     */
    protected void continuousClick() {
        // 每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        // 为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS]; // 重新初始化数组
            mroeClick();
        }
    }

    /**
     * 多次点击的实现，类似于接口，在子类中可直接实现该方法
     */
    protected void mroeClick() {
        if (this instanceof SystemStart_Aty) {
            Intent intent = new Intent("com.MainApp.Action.Exit"); // 发送APP退出的广播
            intent.setComponent(new ComponentName("com.voodoo.appdaemon", "com.voodoo.appdaemon.MyReceiver")); // 括号里为包名+广播类
            sendBroadcast(intent);
            ActivityManager.getInstance().killAllActivity(true);
            finish();
            return;
        }
        String baseUserid = SharedUtils.getInstance().getString(BASEUSERID, "RK_test");
        if (baseUserid.equals("RK_test")|| BuildConfig.DEBUG) {
            startActivity(Settings_Aty.class, null);
        } else {
            startActivity(Login_Aty.class, null);
        }
        finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        cancelCountdownTimer();
        if (EventBus.getDefault().isRegistered(this)) {
            L.i("EventBus，解除绑定", this.getComponentName());
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onNetworkChange(boolean isConnect, NetWorkBroadcastReceiver.NetworkType networkType, int signalStrength, NetWorkBroadcastReceiver.NetworkLevel level) {
        sendNetInfo(level);
        if (connectTypeTv != null) {
            connectTypeTv.setVisibility(View.VISIBLE);
            switch (networkType) {
                case TYPE_NONE: // 无
                    connectTypeTv.setText(getResources().getString(R.string.string_netTypeNone));
                    break;
                case TYPE_ETHERNET: // 网线
                    connectTypeTv.setVisibility(View.GONE);

                    break;
                case TYPE_MOBILE: // 4G
                    connectTypeTv.setText(getResources().getString(R.string.string_netType4G));
                    break;
                case TYPE_WIFI: // WIFI
                    connectTypeTv.setText(getResources().getString(R.string.string_netTypeWifi));
                    break;
                case TYPE_UNKNOW: // 未知
                    connectTypeTv.setText(getResources().getString(R.string.string_netTypeUnknow));
                    break;
            }
        }
        if (signalLevelImgv != null) {
            switch (level) {
                case LEVEL_0:
                    signalLevelImgv.setImageLevel(0);
                    signalLevelTv.setText(getResources().getString(R.string.string_signalNone));
                    break;
                case LEVEL_1:
                    signalLevelImgv.setImageLevel(1);
                    signalLevelTv.setText(getResources().getString(R.string.string_signalFeeble));
                    break;
                case LEVEL_2:
                    signalLevelImgv.setImageLevel(2);
                    signalLevelTv.setText(getResources().getString(R.string.string_signalWeak));
                    break;
                case LEVEL_3:
                    signalLevelImgv.setImageLevel(3);
                    signalLevelTv.setText(getResources().getString(R.string.string_signalMedium));
                    break;
                case LEVEL_4:
                    signalLevelImgv.setImageLevel(4);
                    signalLevelTv.setText(getResources().getString(R.string.string_signalStrong));
                    break;
                case LEVEL_10:
                    signalLevelImgv.setImageLevel(10);
                    signalLevelTv.setText(getResources().getString(R.string.string_signalCable));
                    break;
            }
        }
        if (!isConnect && (this instanceof ShopMain_Aty || this instanceof SystemStart_Aty)) {
            SharedUtils.getInstance().putBoolean(ShareKey.IS_NETWORK_STATUS, true); // 网络异常页
            startActivity(NetWork_Aty.class, null);
            finish();
        }
    }


    /**
     * 设置二维码
     *
     * @param codeimg
     */
    public void setDataSNcode(ImageView codeimg) {
        HashMap<String, String> map = new HashMap<>();
        map.put("version", "Android");
        map.put("sn", DeviceUtils.getDeviceSn());
        String jsonSN = GsonUtils.toJson(map);
        File SnFile = new File(Constant.FilePath.QRCODE_PATH);
        if (!SnFile.exists()) {
            L.i("查询二维码不存在");
            Bitmap SnBitmap = QrcodeUtils.createQrCode(jsonSN);
            FileUtils.saveFile(Constant.FilePath.QRCODE_PATH, SnBitmap);
        }
        GlideImageLoader.getInstance().loadImage(BaseAty.this, Constant.FilePath.QRCODE_PATH, codeimg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void sendNetInfo(NetWorkBroadcastReceiver.NetworkLevel level) {
        int mSendStrength = 0;
        switch (level) {
            case LEVEL_0:
                mSendStrength = 0;
                break;
            case LEVEL_1:
                mSendStrength = 20;
                break;
            case LEVEL_2:
                mSendStrength = 40;
                break;
            case LEVEL_3:
                mSendStrength = 50;
                break;
            case LEVEL_4:
            case LEVEL_10:
                mSendStrength = 60;
                break;
        }
        SharedUtils.getInstance().putInt(ShareKey.SIGNALVALUE, mSendStrength);
    }
}
